﻿using System.Security.Cryptography;
using System.Text;

namespace KuaFu.CardIssuing.OpenApi.Utils
{
    public class SignHelper
    {
        public static bool VerifySign(string merchantId, long timeStamp, string nonceString, string secretKey, string sign)
        {
            var originString = $"{merchantId}&{timeStamp}&{nonceString}&{secretKey}";
            var localSign = MakeSign(originString);

            if (localSign != sign)
                return false;

            return true;
        }

        public static string Sign(string merchantId, long timeStamp, string nonceString, string secretKey)
        {
            var originString = $"{merchantId}&{timeStamp}&{nonceString}&{secretKey}";
            var sign = MakeSign(originString);
            return sign;
        }

        public static string MakeSign(string originString)
        {
            var md5 = MD5.Create();
            var bytes = Encoding.UTF8.GetBytes(originString);
            var hashBytes = md5.ComputeHash(bytes);
            var sb = new StringBuilder();

            foreach (byte b in hashBytes)
                sb.Append(b.ToString("x2"));

            var sign = sb.ToString().ToUpper();

            return sign;
        }
    }
}
